<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class City extends Admin_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model('City_model', 'cityModel');
	}

	public function index()
	{
		$data=$this->data;
		$this->load->view('admin/City/index',$data);
	}
	//页面渲染
	public function index_list()
	{
		$name=$this->input->get('name');
		$limit = $this->input->get('limit');
		$page = $this->input->get('page')==1?0:($this->input->get('page')-1)*$limit;
		$id=$this->input->get('id')==''?0:$this->input->get('id');
		$pid=$this->input->get('pid');
		if(!empty($pid))
		{
			$id=$this->cityModel->getUpId($pid);
		}
		if(empty($name))
		{
			$list=$this->cityModel->getArea($limit,$page,0,['pid'=>$id]);
		}
		else $list=$this->cityModel->getArea($limit,$page,0,['pid'=>$id,'name'=>$name]);
		$result['code'] = 0;
		$result['msg'] = '';
		$result['data'] = $list;
		$result['count'] = $this->cityModel->getAreaLevelCount($id);
		echo json_encode($result);
	}
	//页面渲染
	public function index2()
	{
		$list=$this->cityModel->getAreaList();
		$data=$this->data;
		$data['list']=json_encode($this->getTree($list,0));
		$this->load->view('admin/City/index2',$data);
	}
	//城市递归
	public function getTree($data, $pid)
	{
		$tree = [];
		foreach($data as $k => $v)
		{
			if($v['pid'] == $pid)
			{
				$v['children'] = $this->getTree($data, $v['id']);
				$tree[] = $v;
				unset($data[$k]);
			}
		}
		return $tree;
	}
}
